<script setup lang="ts">
import { ref, reactive, nextTick, computed } from 'vue'
import { Edit, Delete } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCateStore } from '@/stores/cate.js'
import {
  cateFirstService,
  cateSecondService,
  cateThirdService,
  cateDetailService,
  cateUpdateService,
  cateDeleteService,
  cateListService
} from '@/api/cate.js'

// 类型定义
type CategoryLevel = 1 | 2 | 3
type CategoryType = '一级分类' | '二级分类' | '三级分类'

interface Category {
  id: number
  category: string
  fcategory?: string
  scategory?: string
}

interface CategoryForm {
  type: CategoryType
  id?: number
  fId?: number
  sId?: number
  category: string
}

// 组件属性
const props = defineProps<{
  level: CategoryLevel
}>()

// 状态管理
const cateStore = useCateStore()
const tableData = ref<Category[]>([])
const page = ref(1)
const total = ref(0)
const pageSize = 10
const loading = ref(false)
const showDialog = ref(false)
const formRef = ref()
const submitting = ref(false) // 添加提交状态

// 表单数据
const form = reactive<CategoryForm>({
  type: '一级分类',
  id: undefined,
  fId: undefined,
  sId: undefined,
  category: ''
})

// 表单验证规则
const rules = reactive({
  category: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
})

// 计算当前分类类型
const currentCategoryType = computed<CategoryType>(() => {
  return {
    1: '一级分类',
    2: '二级分类',
    3: '三级分类'
  }[props.level] as CategoryType
})

// 获取分类数据
const fetchData = async () => {
  try {
    loading.value = true
    const query = { page: page.value, size: pageSize }
    let service

    switch (props.level) {
      case 1: service = cateFirstService; break
      case 2: service = cateSecondService; break
      case 3: service = cateThirdService; break
    }

    const { data } = await service(query)
    tableData.value = data.records
    total.value = data.total
    tableData.value.forEach((item, index) => {
      item.index = index + 1;
    });
  } catch (error) {
    console.error('获取分类数据失败:', error)
    ElMessage.error('获取分类数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 页码变化处理
const handlePageChange = (newPage: number) => {
  page.value = newPage
  fetchData()
}

// 编辑分类
const handleEdit = async (row: Category) => {
  try {
    loading.value = true
    const { data } = await cateDetailService(props.level, row.id)
    Object.assign(form, {
      id: data.id,
      category: data.category,
      type: currentCategoryType.value
    })
    showDialog.value = true
  } catch (error) {
    console.error('获取分类详情失败:', error)
    ElMessage.error('获取分类详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 删除分类
const handleDelete = (row: Category) => {
  ElMessageBox.confirm(
    `确定要删除分类 "${row.category}" 吗?`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      loading.value = true
      await cateDeleteService(props.level, row.id)
      ElMessage.success('删除成功')
      fetchData()
      cateStore.refreshCateList() // 刷新分类树
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = async () => {
  try {
    submitting.value = true
    await formRef.value.validate()
    // 准备提交数据
    const submitData = {
      type: props.level,
      id: form.id,
      category: form.category
    }
    await cateUpdateService(submitData)
    ElMessage.success('分类修改成功')
    showDialog.value = false
    fetchData()
    cateStore.refreshCateList() // 刷新分类树
  } catch (error) {
    if (error !== 'validate') {
      console.error('修改分类失败:', error)
      ElMessage.error(error.response?.data?.message || '分类修改失败，请稍后重试')
    }
  } finally {
    submitting.value = false
  }
}

// 初始化加载数据
fetchData()
</script>

<template>
  <div class="category-table-container">
    <!-- 分类表格 -->
    <el-table :data="tableData" border stripe v-loading="loading" width="100%">
      <el-table-column prop="index" label="序号" width="80" />

      <el-table-column v-if="level !== 1" prop="fcategory" label="一级分类" width="180" />

      <el-table-column v-if="level === 3" prop="scategory" label="二级分类" width="180" />

      <el-table-column prop="category" label="分类名称" min-width="180" />

      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" circle size="small" @click="handleEdit(row)" />
          <el-button type="danger" :icon="Delete" circle size="small" @click="handleDelete(row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination small background layout="prev, pager, next" :total="total" :current-page="page" :page-size="pageSize"
      class="pagination" @current-change="handlePageChange" />

    <!-- 编辑对话框 -->
    <el-dialog v-model="showDialog" :title="`修改${currentCategoryType}`" width="500px" @closed="formRef?.resetFields()">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类类型" prop="type">
          <el-input v-model="currentCategoryType" disabled />
        </el-form-item>

        <el-form-item label="分类名称" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类名称" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showDialog = false" :disabled="submitting">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          {{ submitting ? '提交中...' : '确认修改' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.category-table-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .pagination {
    margin-top: 16px;
    justify-content: flex-end;
  }
}

:deep(.el-table) {
  flex: 1;

  .el-table__cell {
    padding: 8px 0;
  }
}

:deep(.el-form) {
  padding: 0 20px;

  .el-input {
    width: 100%;
  }
}
</style>